#!/usr/bin/env python
# -*- coding: utf8 -*-

from __future__ import unicode_literals

default_cursor_keyword = 'cursorclass'

try:
	import MySQLdb as mysql
	#import MySQLdb.cursors
	#import MySQLdb.converters
	from MySQLdb.cursors import DictCursor

except ImportError:
	import pymysql as mysql
	from pymysql.cursors import DictCursor

from os3.dbm.dbman import BaseQueryBuilder

class Driver ( object ):
	def __init__ ( self ):
		self.db = None
		self.cursor = None

	def connect ( self, ** kwargs ):
		kwargs [ default_cursor_keyword ] = DictCursor

		self._connection_args = kwargs
		self._connect ()

	def close ( self ):
		try:
			self.db.close ()
		except:
			pass

	def _connect ( self ):
		self.db = mysql.connect ( ** self._connection_args )
		try:
			self.db.autocommit ( True )
		except:
			pass

		self.cursor = self.db.cursor ()

	def placeholders ( self, s ):
		return s.replace ( '?', '%s' )

	def execute ( self, query, params = None ):
		if isinstance ( query, BaseQueryBuilder ):
			query, params = query.get_query_params ()

		# necessario, altrimenti oursql si lamenta che params = None non e' iterabile
		#if params == None: params = tuple ()

		if hasattr ( self.cursor, 'last_query' ):
			self.cursor.last_query = query
			self.cursor.last_query_params = params

		try:
			self.cursor.execute ( query, params )
		except mysql.OperationalError:
			self._connect ()
			self.execute ( query, params )

	def fetchone ( self ):
		try:
			return self.cursor.fetchone ()

		except mysql.ProgrammingError as e:
			return None

	def fetchall ( self ):
		try:
			return self.cursor.fetchall ()

		except mysql.ProgrammingError as e:
			return list ()

	def _last_executed ( self ):
		try:
			return self.cursor._last_executed.decode ( 'latin-1' )
		except:
			return "(query not found)"

	def insert_id ( self ):
		return self.cursor.lastrowid


class QueryBuilder ( BaseQueryBuilder ):
	pass
